<?php

namespace App\Http\Controllers;

use App\BO\UserLocationBO;
use App\Entity\UserEntity;
use App\Services\Code\HttpResponse;
use Illuminate\Support\Facades\Request;

class BaseController extends \Illuminate\Routing\Controller
{
    public static $isGuessLocation = 0;

    /**
     * 成功时的返回
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function successJsonResult($data = [])
    {
        return $this->showJsonResult(200, 'success', $data);
    }

    /**
     * @param int $resCode
     * @param string $rspDesc
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function showJsonResult($resCode = 200, $rspDesc = 'success', $data = [])
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }
        if ($resCode == HttpResponse::CODE_SUCCESS) {
            $result = HttpResponse::respSuccess($resCode, $data, $rspDesc);
        } else {
            $result = HttpResponse::respFail($resCode, $rspDesc);
        }

        //返回结果
        return response()->json($result);
    }

    protected function getUserEntity(): ?UserEntity
    {
        $userId = $this->getUserId();
        if ($userId) {
            return UserEntity::find($userId);
        }
        return null;
    }

    protected function getUserId(): int
    {
        return (int) Request::get('user_id');
    }

    protected function getUserLocationCityId(): int
    {
        if (!$reqLocationCityId = UserLocationBO::getRequestCityId()) {
            self::$isGuessLocation = 1;
            return UserLocationBO::getDefaultCityId();
        }
        return $reqLocationCityId;
    }
}
